<?php

namespace App\Http\Controllers;

use App\Http\Models\Record;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class ExchangeController extends Controller
{

    public function __construct()
    {
        //
    }

    public function exchangeIndex(Request $req) {
        $uid = \Auth::user();
        if (!$uid) return $this->throwError('ErrUnAuthorization');

        $items = $big_sort = [];
        $all_type = DB::table('exchange_type')->get();
        foreach($all_type as $at) {
            $items[$at['id']] = [
                'id' => $at['id'],
                'name' => $at['type_name'],
                'sort' => $at['sort'],
                'stype' => [],
                'show_stype' => $at['show'] ?? 2,
            ];

            $info = DB::table('exchanges')->where('type', $at['id'])->orderBy('sort', 'asc')->get('id');
            if(!empty($info)) {
                foreach ($info as $val) {
                    $big_sort[$at['id']][] = $val['id'];
                }
            }
        }
        $all_stype = DB::table('exchange_type_children')->where('status', 1)->get();
        foreach($all_stype as $ast) {
            $items[$ast['type_id']]['stype'][$ast['id']] = [
                'id' => $ast['id'],
                'name' => $ast['children_name'],
                'sort' => $ast['sort'],
                'list' => [],
            ];
        }

        // $all_items = DB::table('exchanges')->where('home', 1)->orderBy('sort', 'asc')->get();
        $all_items = DB::select('SELECT * FROM exchanges where `home` =1 UNION SELECT * FROM exchanges where `show` =1 ');
        // $have = [];
        foreach($all_items as $ai) {
            if(!isset($items[$ai['type']]['stype'][$ai['stype']]['list'])) continue;
            $items[$ai['type']]['stype'][$ai['stype']]['list'][] = $ai;
            // $have[$ai['id']] = 1;
        }


        $ret = [];
        foreach($items as $i) {
            $tmp = [];
            foreach($i['stype'] as $si) {
                $tmp[] = $si;
            }
            $i['stype'] = $tmp;
            $ret[] = $i;
        }

        return $this->result([
            'list' => $ret,
            'big_sort' => $big_sort,
        ]);
    }

    public function exchangeList(Request $req)
    {
        $type = $req->input('type');
        $stype = $req->input('stype');

        $uid = \Auth::user();
        if (!$uid) return $this->throwError('ErrUnAuthorization');

        $where = ['type' => $type, 'show' => 1];
        if($stype) $where['stype'] = $stype;

        $all_stype = DB::table('exchange_type_children')->where('type_id', $type)->get();
        $stypes = [];
        foreach($all_stype as $at) {
            $stypes[] = [
                'id' => $at['id'],
                'name' => $at['children_name'],
            ];
        }

        $exchange_list = DB::table('exchanges')->where($where)->orderBy('sort', 'asc')->get();
        if(!$exchange_list) $exchange_list = [];

        $coupon_rule = null;
        $goods_rule  = null;
        $config_data = Redis::HGETALL('CONFIG_DATA');
        foreach($config_data as $cd) {
            $cd_arr = json_decode($cd, true);
            if($cd_arr['Name'] == 'couponRule') $coupon_rule = $cd_arr['Val'];
            if($cd_arr['Name'] == 'goodsRule') $goods_rule = $cd_arr['Val'];
        }

        return $this->result([
            'list' => $exchange_list,
            'stypes' => $stypes,
            'coupon' => $coupon_rule,
            'goods' => $goods_rule,
        ]);
    }

    public function exchangeRecord(Request $req) {
        $page = $req->input('page');
        if(!$page || $page < 1) $page = 1;

        $uid = \Auth::user();
        if (!$uid) return $this->throwError('ErrUnAuthorization');

        $start = ($page - 1) * config('game.cfg.BaseRecordPerPage');
        $end = $start + config('game.cfg.BaseRecordPerPage');

        $total = DB::table('exchangerecords')->where('userId', $uid)->count();
        #$get_total = Redis::LLEN('LyfenExchangeRecord:'.$uid);
        if(!$total) $total = 0;
        $total_page = ceil($total / config('game.cfg.BaseRecordPerPage'));

        $records = DB::table('exchangerecords')->where('userId', $uid)->orderBy('id', 'desc')->offset($start)->limit(config('game.cfg.BaseRecordPerPage'))->get();
        if(!$records) $records = [];

        return $this->result([
            'totalpage' => $total_page,
            'list' => $records,
        ]);
    }

    public function exchange(Request $req) {
        $product_id = $req->input('productId');
        $nickname   = $req->input('name');
        $phonenum   = $req->input('phoneNumber');
        $address    = $req->input('address');
        $detail     = $req->input('detailAddr');

        if(!$product_id) return $this->throwError('ErrClientParams');

        $uid = \Auth::user();
        if (!$uid) return $this->throwError('ErrUnAuthorization');

        $uinfo = DB::table('users')->where('id', $uid)->first();
        if(!isset($uinfo['duckId'])) return $this->throwError('ErrGetUser');

        $exchange_data = DB::table('exchanges')->where('productId', $product_id)->first();
        if(!isset($exchange_data['id'])) return $this->throwError('ErrNoThisProduct');

        // 检查星星数量
        if($uinfo['star'] < $exchange_data['needStar']) return $this->throwError('ErrExchangeNoEnoughStar');
        // 检查库存
        if($exchange_data['inventory'] < 1) return $this->throwError('ErrExchangeNoEnoughInventory');

        $today = date('Y-m-d');
        if($uinfo['device_id']) {
            $find_device = DB::table('exchange_limit')->where(['device_id'=>$uinfo['device_id'], 'ex_id'=>$product_id])->first();
            if(isset($find_device['date']) && $find_device['date'] >= $today) {
                return $this->error('兑换失败，每个用户/设备每日仅能兑换一次');
            }
        }

        if($exchange_data['isMaterial'] != 1) {
            // 兑换券
            $uri  =  '/activity-endorsement/endorsement/coupon-activity/v1/coupon';
            // $pstr = 'batchId=' . $product_id . '&clientId=' . config('game.cfg.appid') . '&lyfuid=' . $uinfo['openid'];
            $pstr = 'batchId=' . $product_id . '&clientId=' . env('APPID') . '&lyfuid=' . $uinfo['openid'];

            // $url  = config('game.cfg.origin_api') . $uri . '?' . $pstr;
            $url  = env('ORIGIN_API') . $uri . '?' . $pstr;

            $sig_time = self::now();
            $sig = base64_encode(hash_hmac(
                "sha1",
                "GET\n" .
                $uri . "\n" .
                $pstr . "\n" .
                // "x-co-client:" . config('game.cfg.appid') . "\n" .
                "x-co-client:" . env('APPID') . "\n" .
                "x-co-timestamp:" . $sig_time,
                // config('game.cfg.appsecret'),
                env('APPSECRET'),
                true
            ));
            $headers = [
                'Content-Type:application/json',
                // 'X-Co-Client:' . config('game.cfg.appid'),
                'X-Co-Client:' . env('APPID'),
                'X-Co-TimeStamp:' . $sig_time,
                'X-Co-Sign:' . $sig,
            ];

            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
            $output = curl_exec($ch);
            curl_close($ch);
            $exchange_result = json_decode($output, true);
file_put_contents('/tmp/exchange.log', date('Y-m-d H:i:s')."==================================\n".$output."\n\n", FILE_APPEND);
            if(!isset($exchange_result['code'])) {
                return $this->throwError('ErrLyfenExchange');
            } else {
		if($exchange_result['code'] != 0) {
                	return $this->error($exchange_result['msg']);
		}
            }
        }
        else {
            // 兑换实物
            if(!$nickname || !$phonenum || !$address || !$detail) return $this->throwError('ErrClientParams');
        }

        // 扣星星
        DB::table('users')->where('id', $uid)->decrement('star', $exchange_data['needStar']);
        // 扣库存
        DB::table('exchanges')->where('productId', $product_id)->decrement('inventory', 1);

        // 增加一条记录
        Record::new(
            $uid,
            config('game.cfg.BaseRecordTypeNormal'),
            config('game.cfg.BaseRecordExchange'),
            [$exchange_data['needStar'], $exchange_data['name']]
        );

        // 兑换成功插入兑换记录
        DB::table('exchangerecords')->insert([
            'productId' => $product_id,
            'needStar' => $exchange_data['needStar'],
            'name' => $exchange_data['name'],
            'time' => time(),
            'userId' => $uid,
            'avatar' => $exchange_data['avatar'],
            'nickName' => $exchange_data['type'] == 1 ? '' : $nickname,
            'phoneNumber' => $exchange_data['type'] == 1 ? '' : $phonenum,
            'address' => $exchange_data['type'] == 1 ? '' : $address,
            'detailAddr' => $exchange_data['type'] == 1 ? '' : $detail,
            'type' => $exchange_data['type'],
            'sname' => $exchange_data['sname'],
            'status' => $exchange_data['type'] == 1 ? 1 : 0,
            'isMaterial' => $exchange_data['isMaterial'],
            'jump' => $exchange_data['jump'],
        ]);

        if($uinfo['device_id']) {
            DB::statement("REPLACE INTO exchange_limit values ('" . $uinfo['device_id'] . "', '" . $product_id . "', '" . date('Y-m-d') ."')");
        }

        return $this->result([]);
    }

}
